package com.zhike.api.controller.system;

import java.util.Observable;
import java.util.Observer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zhike.common.dto.LoginDTO;
import com.zhike.common.dto.R;
import com.zhike.common.model.Device;
import com.zhike.common.utils.IpHelper;
import com.zhike.common.vo.LoginResponse;
import com.zhike.common.vo.UserInfo4Cache;
import com.zhike.mobileimsdk.server.protocal.c.PLoginInfo;
import com.zhike.service.im.client.IMClientManager;
import com.zhike.service.im.client.core.LocalDataSender;
import com.zhike.service.system.ISystemService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
@RestController
@RequestMapping("api/zkim/sys")
@Api(tags = "系统模块")
@Slf4j
public class SysUserController {

    @Resource
    private ISystemService systemService;

    @Autowired
    private IMClientManager imClientManager;

    @Autowired
    private LocalDataSender localDataSender;

    @ApiOperation(value = "用户登录接口")
    @PostMapping("userLogin")
    public R<LoginResponse> userLogin(@Validated @RequestBody LoginDTO dto, HttpServletRequest request) {
        return systemService.login(dto, IpHelper.getIpAddr(request));
    }

    @ApiOperation(value = "用户退出接口")
    @PostMapping("userLogOut")
    public R<Boolean> logOut(HttpServletRequest req) {
        return R.success(systemService.logout(req));
    }

    // @ApiIgnore
    @ApiOperation(value = "IM登录")
    @PostMapping("imLogin")
    public R<Integer> imLogin(@RequestBody LoginDTO dto) {
        Observer onLoginSucessObserver = new Observer() {
            @Override
            public void update(Observable observable, Object data) {
                // 服务端返回的登陆结果值
                int code = (Integer) data;
                // 登陆成功
                if (code == 0) {
                    log.info("{} success login", dto.getLoginAccount());
                }
            }
        };
        imClientManager.getBaseEventListener().setLoginOkForLaunchObserver(onLoginSucessObserver);
        UserInfo4Cache uc = systemService.getUserInfo();
        String deviceNo = "";
        for (Device d : uc.getDeviceList()) {
            if (d.getDeviceType().equals(dto.getDeviceType())) {
                deviceNo = d.getDeviceNo();
                break;
            }
        }

        PLoginInfo loginInfo = new PLoginInfo(deviceNo, dto.getLoginPassword());

        int code = localDataSender.sendLogin(loginInfo);
        return R.success(code);
    }
}
